package cn.cjlmonster.demo02.utils;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/23 11:46 下午.
 */
public class JTools {

    private static final Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .create();

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T toObj(String jsonString, Class<T> classOfT) {
        return gson.fromJson(jsonString, classOfT);
    }

    public static <T> List<T> toList(String jsonString, Class<T> classOfT) {
        Type type = new ParameterizedTypeImpl<>(classOfT);
        return gson.fromJson(jsonString, type);

    }

    private static class ParameterizedTypeImpl<T> implements ParameterizedType {

        private final Class<T> clazz;

        public ParameterizedTypeImpl(Class<T> clz) {
            clazz = clz;
        }

        @NonNull
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @NonNull
        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }

}
